# 获取excel文件路径
import json

from utils.handle_path import *
from openpyxl import load_workbook
import os

EXPECTED_HEADERS = ['用例ID', '模块', '用例级别', '正反案例', '案例名称', '预期结果', '设计人', '是否有效', '测试结果',
                    '是否通过', 'url', 'method', 'data']


class HandleExcel():
    def __init__(self, filename):
        self.filename = filename
        if not os.path.exists(filename):
            raise FileNotFoundError('测试用例文件不存在！')
        self.wb = load_workbook(filename=filename)
        # 校验表头
        try:
            header_row = self.wb.active[1]
            header_data = [cell.value for cell in header_row]
            # print(header_data)
            if header_data != EXPECTED_HEADERS:
                raise Exception('表头错误！')
        except(IndexError, AttributeError) as e:
            print(f'表头获取异常！:{e}')

    def get_data(self, row_number):
        """获取指定行数据"""
        if row_number < 1:
            raise ValueError('行号不能小于1！')
        try:
            target_row = self.wb.active[row_number]
            row_data = [cell.value for cell in target_row]
            return row_data
        except IndexError:
            raise IndexError(f'行号{row_number}越界')

    def write_data(self, row_number, result, is_pass):
        """实现写入指定行测试结果，更新数据"""
        if row_number < 1:
            raise ValueError('行号不能小于1！')
        try:
            target_row = self.wb.active[row_number]
            # row_data = [cell.value for cell in target_row]
            target_row[8].value = result
            target_row[9].value = is_pass
            self.wb.save(self.filename)
        except IndexError:
            raise IndexError(f'行号{row_number}越界')
        except Exception as e:
            raise Exception(f'写入数据异常！{e}')


# test = HandleExcel(data_path + '/' + 'testcase.xlsx')
# print(data_path + '/' + 'testcase.xlsx')
# print(test.get_data(row_number=2))
# case_file = data_path + '/' + 'testcase.xlsx'
# print(case_file)
ex = HandleExcel(data_path + '/' + 'testcase.xlsx')
print(json.loads(ex.get_data(row_number=2)[5])['errcode'])